package problem143;

//143.重排链表
//https://leetcode.cn/problems/reorder-list/

class Solution2 {
    public void reorderList(ListNode head) {
        //找到链表中间节点
        ListNode slow = head, fast = head.next;
        while(fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }

        //翻转后半部分链表
        ListNode tmp = slow.next;
        ListNode newHead = new ListNode();
        while(tmp != null) {
            ListNode next = tmp.next;
            tmp.next = newHead.next;
            newHead.next = tmp;
            tmp = next;
        }
        slow.next = null;

        //合并两个链表
        ListNode cur1 = head, cur2 = newHead.next;
        ListNode newHead2 = new ListNode();
        ListNode cur = newHead2;
        while(cur1 != null && cur2 != null) {
            ListNode next = cur1.next;
            cur.next = cur1;
            cur1.next = cur2;

            cur1 = next;
            cur2 = cur2.next;
            cur = cur.next.next;
        }
        if(cur1 != null) cur.next = cur1;
        head = newHead.next;
    }
}